package com.sumer.psychology.friend.application.query;

import com.sumer.psychology.common.domain.model.User;
import com.sumer.psychology.common.domain.model.UserService;
import com.sumer.psychology.friend.domain.model.Member;
import com.sumer.psychology.friend.domain.model.MemberId;
import com.sumer.psychology.friend.domain.model.MemberRepository;
import org.apache.commons.collections.CollectionUtils;

import javax.transaction.Transactional;
import java.util.HashSet;
import java.util.Set;

/**
 * 朋友查询
 * <p/>
 * Created by twer on 15/3/23.
 */
@Transactional
public class FriendshipQueryApplicationService {
    private MemberRepository memberRepository;
    private UserService userService;


    public FriendshipQueryApplicationService(MemberRepository memberRepository, UserService userService) {
        this.memberRepository = memberRepository;
        this.userService = userService;
    }

    /**
     * 所有的好友
     *
     * @param aMemberId member
     * @return users
     */
    public Set<User> friendsOfMemberId(String aMemberId) {
        Member member = memberRepository().memberOfId(new MemberId(aMemberId));
        if (member == null) {
            return new HashSet<>(0);
        }
        Set<MemberId> friends = member.friends();

        return usersFromMemberIds(friends);
    }

    /*
     * 从member映射到users
     */
    private Set<User> usersFromMemberIds(Set<MemberId> friends) {
        Set<User> users = new HashSet<>();
        if (CollectionUtils.isNotEmpty(friends)) {
            for (MemberId friend : friends) {
                User user = userService().userFrom(friend.identity());
                users.add(user);
            }
        }
        return users;
    }

    private MemberRepository memberRepository() {
        return memberRepository;
    }

    private UserService userService() {
        return userService;
    }
}
